﻿using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using Microsoft.Web.Mvc;

namespace Peak.Web.Controllers.Models
{
  public static class HtmlPagerExtension
  {
    public static string Pager<T>(this HtmlHelper helper, int currentPage, int currentPageSize, int totalRecords, Expression<Action<T>> action)where T : Controller
    {
      string template = "<a href=\"{0}?page={1}\">{2}</a>";
      StringBuilder sb1 = new StringBuilder();
      string urlPrefix = helper.BuildUrlFromExpression(action);

      int seed = currentPage % currentPageSize == 0 ? currentPage : currentPage - (currentPage % currentPageSize);

      if (currentPage > 0)
        sb1.AppendLine(String.Format(template,urlPrefix,currentPage-1,"Previous"));

      if (currentPage - currentPageSize >= 0)
        sb1.AppendLine(String.Format(template,urlPrefix, (currentPage - currentPageSize) + 1,"..."));

      for (int i = seed; i < Math.Round((totalRecords / currentPageSize) + 0.5) && i < seed + currentPageSize; i++)
      {
        if (i == currentPage)
          sb1.AppendLine((i + 1).ToString());
        else
          sb1.AppendLine(String.Format(template, urlPrefix, i, i + 1));
      }

      if (currentPage + currentPageSize <= (Math.Round((totalRecords / currentPageSize) + 0.5) - 1))
        sb1.AppendLine(String.Format(template, urlPrefix, (currentPage + currentPageSize) + 1,"..."));

      if (currentPage < (Math.Round((totalRecords / currentPageSize) + 0.5) - 1))
        sb1.AppendLine(String.Format(template, urlPrefix, currentPage + 1,"Next"));

      return sb1.ToString();
    }
  }
}